package com.chuangyang.fixboxmaster.ui.fragment.orderprice;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.CostItem;
import com.chuangyang.fixboxmaster.bean.Part;
import com.chuangyang.fixboxmaster.listener.PartNumChangeListener;
import com.chuangyang.fixboxmaster.ui.ApplianceInfoActivity;
import com.chuangyang.fixboxmaster.ui.ModuleActivity;
import com.chuangyang.fixboxmaster.ui.adapter.SelectPartListAdapter;
import com.chuangyang.fixboxmaster.ui.fragment.BaseFragment;

import java.util.ArrayList;

/**
 * Created by Administrator on 2015/6/11.
 */
public class PriceFragment extends BaseFragment implements View.OnClickListener , AdapterView.OnItemClickListener,PartNumChangeListener{

    private View mContentView;

    private ListView mPartsListView;

    private TextView mAddPartView;

    private TextView mPriceView;

    private TextView mOKView;

    private ArrayList<Part> mParts = new ArrayList<>();

    private SelectPartListAdapter mAdapter;

    private String mOrderID;

    private String mTransactionId;
    private String mSpecificationId;
    private String mProductDate;
    private String mBrandId;

    private ArrayList<CostItem> mTypeList = new ArrayList<>();

    public static final int RESQUEST_CODE_PART = 1;

    private CostItem mRepairTYpe;

    public static final int REQUEST_CODE_REPAIR_TYPE = 2;

    private AlertDialog mRemovePartDlg;

    public static PriceFragment newInstance(){
        return new PriceFragment();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_price,container,false);
        Bundle bundle = getArguments();
        if (bundle != null)
        {
            mParts = (ArrayList<Part>)bundle.getSerializable(ModuleActivity.SELECT_PART);
            mOrderID = bundle.getString(ModuleActivity.ORDER_ID);
            mTransactionId = getArguments().getString(ModuleActivity.TRANSCATION_ID);
            mSpecificationId = getArguments().getString(ModuleActivity.SPECIFICATION_ID);
            mProductDate = getArguments().getString(ModuleActivity.PRODUCT_DATE);
            mBrandId = getArguments().getString(ModuleActivity.BRAND_ID);
            mRepairTYpe = (CostItem)bundle.getSerializable(ModuleActivity.REPAIR_TYPE);
            mTypeList = (ArrayList<CostItem>)bundle.getSerializable(ModuleActivity.COST_ITEM);
        }
        Part part = getFixPrice();
        mParts.add(0,part);
        initView();


        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void initView(){

        mPartsListView = (ListView)mContentView.findViewById(R.id.part_list);
        mAddPartView = (TextView)mContentView.findViewById(R.id.add_part);
        mAddPartView.setOnClickListener(this);
        mPriceView = (TextView)mContentView.findViewById(R.id.total_price);
        mOKView = (TextView)mContentView.findViewById(R.id.btn_ok);
        mOKView.setOnClickListener(this);

        mAdapter = new SelectPartListAdapter(mParts);
        mPartsListView.setAdapter(mAdapter);
        mPartsListView.setOnItemClickListener(this);
        mAdapter.setNumberChangeListener(this);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        setTotalPrice();
        showResult();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_ok:
                Intent costDetailIntent = new Intent(getActivity(), ModuleActivity.class);
                costDetailIntent.putExtra(ModuleActivity.TYPE, ModuleActivity.COST_DETAIL_ACTIVITY);
                costDetailIntent.putExtra(ModuleActivity.ORDER_ID, mOrderID);
                costDetailIntent.putExtra(ApplianceInfoActivity.TRANSCATION_ID, mTransactionId);
                costDetailIntent.putExtra(ApplianceInfoActivity.SPECIFICATION_ID, mSpecificationId);
                costDetailIntent.putExtra(ApplianceInfoActivity.PRODUCT_DATE, mProductDate);
                costDetailIntent.putExtra(ApplianceInfoActivity.BRAND_ID,mBrandId);
                costDetailIntent.putExtra(ModuleActivity.COST_ITEM, getCostItem());
                startActivity(costDetailIntent);

                break;
            case R.id.add_part:
                if (mRepairTYpe.type == 4)
                {
                    Toast.makeText(getActivity(), "请选择维修类别!", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Intent partIntent = new Intent(getActivity(), ApplianceInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt(ApplianceInfoActivity.TYPE, ApplianceInfoActivity.APPLIANCE_PART_ACTIVITY);
                    bundle.putString(ApplianceInfoActivity.SPECIFICATION_ID,""+mSpecificationId);
                    bundle.putString(ApplianceInfoActivity.TRANSCATION_ID,""+mTransactionId);
                    bundle.putString(ApplianceInfoActivity.ORDER_ID,""+mOrderID);
                    bundle.putString(ApplianceInfoActivity.PRODUCT_DATE,""+mProductDate);
                    bundle.putString(ModuleActivity.BRAND_ID, mBrandId);
                    bundle.putSerializable(ModuleActivity.REPAIR_TYPE,mRepairTYpe);
                    if (mParts.size() > 0)
                        mParts.remove(0);
                    bundle.putSerializable(ApplianceInfoActivity.SELECT_PART,mParts);
                    partIntent.putExtras(bundle);
                    startActivityForResult(partIntent, RESQUEST_CODE_PART);
                }
                break;
        }
    }

    private ArrayList<CostItem> getCostItem(){
        ArrayList<CostItem> items = new ArrayList<>();

        if (mParts != null)
        {
            for (Part part:mParts)
            {
                CostItem item = new CostItem();

                if (mRepairTYpe.type == 4)
                {
                    item.title = mRepairTYpe.title;
                    item.price = mRepairTYpe.price;
                    item.num = mRepairTYpe.num;
                    item.type = 1;
                    item.partId = 0;
                    items.add(item);
                }
                else
                {
                    item.title = part.title;
                    item.price = part.suggestPrice;
                    item.num = part.num;

                    if (item.num > 0)
                    {
                        if (part.title.equals("维修费"))
                        {
                            item.type = 2;
                            item.partId = 0;
                        }
                        else if (part.specificationId > 0)
                        {
                            item.type = 3;
                            item.partId = part.id;

                        }
                        else
                        {
                            item.type = 3;
                            item.partId = 0;

                        }

                        items.add(item);
                    }
                }
            }
        }
        return items;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case  PartFragment.REQUEST_CODE_ADD_PART:

                if (data != null)
                {
                    Bundle bundle = data.getExtras();
                    if (bundle != null)
                    {

                        Object object = bundle.getSerializable(ApplianceInfoActivity.SELECT_PART);
                        if (object != null)
                        {
                            mParts = (ArrayList<Part>)object;

                            if (mParts.size() <= 0)
                            {
                                getActivity().finish();
                            }
                            else
                            {
                                Part part = getFixPrice();
                                mParts.add(0,part);
                                mAdapter = new SelectPartListAdapter(mParts);
                                mPartsListView.setAdapter(mAdapter);
                                mAdapter.setNumberChangeListener(this);
                            }

                        }
                    }
                }
                break;
            case  REQUEST_CODE_REPAIR_TYPE:
                if (checkPartNull())
                {
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            CostItem item = (CostItem)bundle.getSerializable("cost_item");
                            if (item != null)
                            {
                                mRepairTYpe = item;
                                Part part = getFixPrice();
                                if (item.type == 4)
                                {
                                    part.title = "上门诊断费";
                                }
                                mParts.set(0,part);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                }
                break;
        }
    }

    private Part getFixPrice(){

        Part part = new Part();
        part.title = "维修费";
        part.num = 1;
        part.suggestPrice = 0;

        if (mParts != null)
        {
            for (Part obj:mParts)
            {
                if (obj.num > 0)
                {
                    if (obj.fixPrice > part.suggestPrice)
                        part.suggestPrice = obj.fixPrice;
                }
            }
        }
        if (part.suggestPrice <= 0)
        {
            part.suggestPrice = mRepairTYpe.price;
        }

        return part;
    }

    private boolean checkPartNull(){
        boolean result = true;
        if (mParts != null)
        {
            for (int i = 1; i < mParts.size();i++)
            {
                Part part = mParts.get(i);
                if (part.num > 0)
                    return false;
            }
        }
        return result;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Part part = mParts.get(position);

        if (part != null)
        {
            if (position == 0)//维修费
            {
                if (checkPartNull())
                {
                    Intent repairTypeIntent = new Intent(getActivity(), ModuleActivity.class);
                    repairTypeIntent.putExtra(ModuleActivity.TYPE, ModuleActivity.REPAIR_TYPE_ACTIVITY);
                    repairTypeIntent.putExtra(ModuleActivity.REPAIR_TYPE, mRepairTYpe);
                    repairTypeIntent.putExtra(ModuleActivity.COST_ITEM, mTypeList);
                    startActivityForResult(repairTypeIntent,REQUEST_CODE_REPAIR_TYPE);
                }
            }
        }
        Log.e("","");
    }



    @Override
    public void onChange(Part part) {

        if (part.num > 0)
        {
            mParts.remove(0);
            Part item = getFixPrice();
            mParts.add(0,item);
            setTotalPrice();
            mAdapter.notifyDataSetChanged();
        }
        else
        {
            showRemovePartDlg(part);

        }
    }

    private void showRemovePartDlg(final Part part){

        AlertDialog.Builder cancelOrderDlg = new AlertDialog.Builder(getActivity());
        cancelOrderDlg.setMessage("您是否要删除配件("+part.title+")");
        cancelOrderDlg.setCancelable(false);
        cancelOrderDlg.setNegativeButton("否",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                part.num = 1;
                setTotalPrice();
                mAdapter.notifyDataSetChanged();
            }
        });
        cancelOrderDlg.setPositiveButton("是",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mParts.remove(part);
                mParts.remove(0);
                Part item = getFixPrice();
                mParts.add(0,item);
                setTotalPrice();
                mAdapter.notifyDataSetChanged();
            }
        });
        mRemovePartDlg = cancelOrderDlg.create();
        mRemovePartDlg.show();
    }

    private void setTotalPrice(){

        int totalPrice = 0;

        for (Part part:mParts)
        {
            totalPrice += part.num*part.suggestPrice;
        }

        mPriceView.setText("合计: ￥" +totalPrice);
    }

    @Override
    public ListView getListView() {
        return mPartsListView;
    }
}
